/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package koor.action.teacher;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import koor.action.Action;
import koor.action.ActionResult;
import koor.entity.Teacher;
import koor.persistent.TeacherDAO;
import koor.service.ServiceLocator;

/**
 * The
 * <code>TeacherAction</code> class represents action, used to view teacher
 * information
 *
 * @author Admin
 */
public class TeacherAction implements Action {

    @Override
    public String getName() {
        return "teacher.view";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        TeacherDAO teacherDAO = ServiceLocator.getService(TeacherDAO.class);

        if ((request.getParameter("id") != null) || (request.getSession().getAttribute("id") != null)) {
            try {
                Long id = (request.getParameter("id") != null) ? (Long.parseLong(request.getParameter("id"))) : ((Integer) request.getSession().getAttribute("id"));
                Teacher teacher = teacherDAO.findOne(id);
                request.setAttribute("teacher", teacher);
                return ActionResult.forward("TeacherView/TeacherView.jsp");
            } catch (NumberFormatException e) {
                request.setAttribute("fail", "Неверный номер");
            } catch (RuntimeException e) {
                request.setAttribute("fail", "Преподаватель не найден");
            }
        }

        List<Teacher> teacherList = teacherDAO.findAll();
        request.setAttribute("teacherList", teacherList);
        return ActionResult.forward("TeacherView/TeacherListView.jsp");
    }
}
